package cn.ncist.jobs;

import cn.ncist.constant.RedisConstant;
import cn.ncist.utils.QiNiuUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Set;

/**
 * 自定义job，实现定时清理垃圾图片
 */
public class ClearImgJob extends QuartzJobBean {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        //根据Redis中保存的两个set集合进行差值计算，获得垃圾图片名称集合
        Set<String> set = null;
        try {
            set = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES,RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(set != null){
            for (String picName : set) {
                //删除废弃的图片
                try {
                    QiNiuUtil.deleteFileFromQiniu(picName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES,picName);
            }
        }
    }
}
